package net.xdclass.springboot.controller;

import net.xdclass.springboot.domain.JsonData;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
@PropertySource("classpath:application.properties")
public class FileController {

    /**
     * 处理根路径的GET请求
     * idea springboot项目
     * 该方法不需要接收任何参数，因此使用@GetMapping注解来映射根路径的GET请求
     * 主要用途是当用户访问应用的根URL时，返回一个简单的欢迎消息
     *
     * @return 返回欢迎消息字符串"Hello, Spring Boot!"
     */

    // 需要引入Thymeleaf模板引擎
    @RequestMapping(value="/api/v1/gopage")
    public Object index() {
        return "index1";
    }


//    private static final String UPLOAD_DIR = "F:\\gitworkspace\\springboot\\src\\main\\resources\\static\\images\\";
    @Value("${web.images-path}")
//    @Value("${web.file.path}")
    private String UPLOAD_DIR;

    @RequestMapping("/upload")
    @ResponseBody
    public JsonData handleFileUpload(@RequestParam("file") MultipartFile file, String name) {
        System.out.println("用户名：" + name);
        String fileName = file.getOriginalFilename();
        System.out.println("文件名：" + fileName);

        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        System.out.println("文件后缀名：" + suffixName);

        fileName = UUID.randomUUID() + suffixName;
        System.out.println("转换后文件名：" + fileName);
        File dest = new File(UPLOAD_DIR + "\\" + fileName);


        try {
          file.transferTo(dest);
            return new JsonData(0, fileName,"上传成功");
        } catch (IOException e) {
            e.printStackTrace();
        }

        return new JsonData(-1,  fileName,"上传失败");
    }
}